import { reqGetUserInfo, reqLogin, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 存token
    setToken(state, newToken) {
      state.token = newToken
      // 将token存到cookies中
      setToken(newToken)
    },
    // 存用户信息
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    // 删除token
    removeToken(state) {
      state.token = ''
      // 清除本地的token
      removeToken()
    },
    // 删除用户的信息
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 发请求，拿token
    async login(context, data) {
      const res = await reqLogin(data)
      console.log(res)
      const newToken = res.data
      context.commit('setToken', newToken)
      // console.log(1111)
    },
    // 获取用户资料
    async getUserInfo(context) {
      const { data: data1 } = await reqGetUserInfo() // 用户的基本资料
      const { data: data2 } = await reqGetUserDetailById(data1.userId)// 包含头像的资料
      const res = { ...data1, ...data2 }
      console.log(res)
      context.commit('setUserInfo', res)
      return res
    },
    logout({ commit }) {
      // 删除token
      commit('removeToken')
      // 删除用户资料
      commit('removeUserInfo')
    }
  }
}
